﻿using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using QuickGet.Core.Models;
using QuickGet.Core.Stores;
using QuickGet.EntityFrameworkCore.Models;

namespace QuickGet.EntityFrameworkCore.Stores
{
    public class PackageSourceStore : StoreBase, IPackageSourceStore
    {
        public PackageSourceStore(AppDbContext appDbContext,
            ILogger<PackageSourceStore> logger) : base(appDbContext, logger) { }

        public async Task CreateAsync(PackageSourceInfo source, CancellationToken cancellationToken)
        {
            var duplicated = await CheckDuplicatedAsync(source.Name, cancellationToken);

            if (duplicated)
            {
                throw new InvalidOperationException($"Duplicated name: '{source.Name}'");
            }

            var entity = new PackageSourceEntity(source.Name, source.Source)
            {
                IsEnabled = source.IsEnabled,
            };

            AppDb.Add(entity);

            await AppDb.SaveChangesAsync(cancellationToken);
        }

        private async Task<bool> CheckDuplicatedAsync(string name, CancellationToken cancellationToken)
        {
            var query = AppDb.PackageSources.Where(x => x.Name == name);

            var count = await query.CountAsync(cancellationToken);

            return count > 0;
        }

        public async Task<List<PackageSourceInfo>> ListAsync(CancellationToken cancellationToken)
        {
            var query = AppDb.PackageSources
                .AsNoTracking()
                .ProjectToType<PackageSourceInfo>();

            return await query.ToListAsync(cancellationToken);
        }

        public async Task SetEnabledAsync(string name, bool isEnabled, CancellationToken cancellationToken)
        {
            var entity = await AppDb.PackageSources
                .Where(x => x.Name == name)
                .FirstOrDefaultAsync(cancellationToken);

            if(entity is null)
            {
                throw new InvalidOperationException($"Cannot found package source: '{name}'");
            }

            entity.IsEnabled = isEnabled;

            await AppDb.SaveChangesAsync(cancellationToken);
        }

        public async Task<PackageSourceInfo?> GetAsync(string name, CancellationToken cancellationToken)
        {
            var query = AppDb.PackageSources
                .Where(x => x.Name == name)
                .ProjectToType<PackageSourceInfo>();

            return await query.FirstOrDefaultAsync(cancellationToken);
        }
    }
}
